# coding=utf-8
import json as pyjson
from django.http import HttpResponse
from django.db.models.query import QuerySet
from django.core.cache import cache
from xadmin.views.base import JSONEncoder
from models import Product, Category, Adv, Order, Good, INFOS
from forms import OrderForm

item_infos_dict = dict(INFOS)

def static_media_url(url):
    return url

def file_url(f, tag='phone', screen_hr=False, rotate=-90):
    if f is None:
        return ''

    if screen_hr:
        tag += "_hr"

    #if f is url
    if type(f) in (str, unicode):
        if f.startswith('http://'):
            return unicode(f)
        else:
            return static_media_url(unicode(f))
    try:
        key = '%s:%s:%s' % ('img', f.url, tag)
        url = cache.get(key)
        if url is not None:
            return url

        if hasattr(f, 'extra_thumbnails') and f.extra_thumbnails.has_key(tag):
                f = f.extra_thumbnails[tag]
        if hasattr(f, 'url'):
            url = f.url
        else:
            url = static_media_url(unicode(f))
            
        cache.set(key, url, 100 * 60)
        return url
    except Exception, e:
        print e
        return ''

def get_screen_shots(item):
    shots_url = []
    for ss in item.pics.all():
        image = ss.image
        if image:
            f_url = file_url(image)
            if f_url:
                f_url = {'small': file_url(image), 'big': file_url(image.url)}
                shots_url.append(f_url)
    return shots_url

def get_item_infos(item):
    return dict([(item_infos_dict[info.name], info.value) for info in item.infos.all()])

def convert_item(item):
    info = {'id': item.id, 'name': item.name, "slug":item.slug, \
        'category': item.category.name, 'icon': file_url(item.logo), 'level': item.level}
    prices = item.prices.all()
    if prices:
        info['price'] = prices[0].price
        info['price_id'] = prices[0].id
    else:
        info['price'] = '暂无价格'
    return info

def convert_item_info(item):
    info = convert_item(item)

    info['screenshots'] = get_screen_shots(item)
    info['infos'] = get_item_infos(item)
    info["publish_time"] = item.publish_time
    info["description"] = item.introduction
    info["icon_full"] = file_url(item.logo, "full")

    return info

def convert_adv(ad):
    info = {'pic': file_url(ad.pic), 'product_id': ad.product.id}
    return info
    
def convert_category(c):
    info = {'icon': file_url(c.icon), 'id': c.id, 'name': c.name, 'description': c.description}
    return info
    

def json(request, chunk):
    if request.REQUEST.get('windowname', 'false') == 'true':
        html = '<html><script type="text/javascript">window.name=\'%s\';</script></html>'
        if type(chunk) in (dict, list):
            chunk = pyjson.dumps(chunk, cls=JSONEncoder, ensure_ascii=False)
        return HttpResponse(html % chunk.replace("'", "\\'").replace('\r\n', ' '))
    else:
        return HttpResponse(pyjson.dumps(chunk, cls=JSONEncoder, ensure_ascii=False))

def ps(request, qs, convert_func=None, **kwargs):
    start = int(request.GET.get('start', 0))
    count = int(request.GET.get('count', 25))

    if(start < 0 or count > 100 or count < 0):
        raise Exception(u"分页参数错误")

    if (type(qs) in (list, set)):
        total_count = len(qs)
    else:
        total_count = qs.count()
        if type(qs) not in (QuerySet,):
            qs = qs.all()

    if total_count > 0:
        if start == -1:
            import math

            start = int(math.ceil(float(total_count) / count) - 1) * count
        qs = qs[start:start + count]
        items = convert_func is None and qs or [convert_func(item, **kwargs) for item in qs]
    else:
        items = []
    return {'total_count': total_count, 'items': items}

def advs(request):
    return json(request, [convert_adv(ad) for ad in Adv.objects.filter(user=request.GET['userid'])])
    
def items(request, mode="feature"):
    if mode == "feature":
        items = Product.objects.filter(user=request.GET['userid'])
    elif mode == "category":
        items = Product.objects.filter(user=request.GET['userid'], category=request.GET['category_id'])
    elif mode == 'search':
        items = Product.objects.filter(user=request.GET['userid'], name__contains=request.GET['name'])
        
    return json(request, ps(request, items, convert_item))

def item(request):
    item = Product.objects.get(id=request.GET['id'])
    return json(request, convert_item_info(item))

def categorys(request):
    if request.GET.has_key('category_id'):
        try:
            cate = Category.objects.get(id=request.GET['category_id'])
            context = ps(request, cate.products, convert_item)
            context['category_id'] = cate.id
        except Exception:
            context = ps(request, [], convert_item)
            context['category_id'] = request.GET['category_id']
    
        return json(request, context)
    else:
        return json(request, ps(request, Category.objects.filter(user=request.GET['userid']).order_by('sort'), convert_category))

def order(request):
    goods = []
    for gstr in request.GET['goods'].split(';'):
        gs = gstr.split('|')
        p = Product.objects.get(pk=gs[0])
        price = p.prices.get(pk=gs[1])
        goods.append(Good(product=p, price=price.price, count=int(gs[2])))

    if not goods:
        return json(request, {'success': False})

    total = sum([g.price * g.count for g in goods])

    f = OrderForm(request.GET)

    if f.is_valid():
        order = f.save(commit=False)

        order.uuid = request.COOKIES['uuid']
        order.amount = total
        order.user = goods[0].product.user

        order.save()

        for g in goods:
            g.order = order
            g.save()

        return json(request, {'success': True})
    else:
        return json(request, {'success': False})

